package com.rickie.hello.rsocket.controller;

import com.rickie.hello.rsocket.model.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Controller;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;


@Controller
@Slf4j
public class HelloController {

    @MessageMapping("hello")
    public Mono<String> hello(Mono<String> helloMono) {
        return helloMono
                .doOnNext(hello -> log.info("接收到的消息：{} ", hello))
                .map(hello -> "来自HelloController.hello() 的响应消息");
    }

    @MessageMapping("hello/{name}")
    public Mono<String> hello(
            @DestinationVariable String name,
            Mono<String> helloMono
    ) {
        return helloMono
                .doOnNext(hello -> log.info("从{} -> 接收到的消息：{} ", name, hello))
                .map(hello -> "返回消息给 -> " + name);
    }

    @MessageMapping("hello/employees/{dept}")
    public Flux<Employee> getEmployeesByDept(
            @DestinationVariable String dept
    ) {
        log.info("部门：{}",dept) ;

        return Flux
                .interval(Duration.ofSeconds(1))
                .map(i -> {
                    Integer id = Integer.valueOf(Integer.parseInt(randomNumeric(2)));
                    return new Employee(
                                id,
                                randomAlphabetic(6));
                        }
                    );
    }
}
